
<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="80px">
          <el-form-item label="标题" prop="consult_wz_title">
            <el-input
              v-model="queryParams.consult_wz_title"
              placeholder="请输入标题"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              size="small"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <div>
          <el-row :gutter="16" class="mb10" style="float:right">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">
                <span>新增</span>
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
              >删除</el-button>
            </el-col>
          </el-row>
        </div>
        <el-table
          v-loading="loading"
          :data="sysArticleList"
          border
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChang"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="文章标题"
            header-align="center"
            prop="consult_wz_title"
            width="260px"
            :show-overflow-tooltip="true"
          />
          <el-table-column prop="wz_url" label="文章封面" header-align="center">
            <template slot-scope="scope">
              <el-image
                :preview-src-list="[scope.row.wz_url]"
                :src="scope.row.wz_url"
                style="width: 140px; height: 80px"
              />
            </template>
          </el-table-column>

          <el-table-column
            label="描述"
            header-align="center"
            align="left"
            prop="consult_wz_introduction"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.consult_wz_introduction }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createdAt">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="120px"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                :disabled="!multiple && single"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改对话框 -->
        <el-drawer
          ref="drawer"
          :title="title"
          :visible.sync="open"
          direction="rtl"
          size="60%"
          custom-class="demo-drawer"
        >
          <div class="demo-drawer__content">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-form-item label="文章标题" prop="consult_wz_title">
                <el-input v-model="form.consult_wz_title" placeholder="请输入文章标题" />
              </el-form-item>
              <el-form-item label="文章封面" prop="wz_url">
                <el-upload
                  :headers="headers"
                  :action="$uploadUrl"
                  list-type="picture-card"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :on-success="uploadSuccess"
                  :on-remove="handleRemove"
                >
                  <el-image v-if="form.wz_url" :src="form.wz_url" class="upload-image" />
                  <i v-else class="el-icon-plus" />
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
              </el-form-item>
              <el-form-item label="置顶" prop="wz_top">
                <el-switch
                  v-model="form.wz_top"
                  style="width: 40%"
                  :active-value="1"
                  :inactive-value="2"
                  active-text="是"
                  inactive-text="否"
                />
              </el-form-item>
              <el-form-item label="描述" prop="consult_wz_introduction">
                <el-input v-model="form.consult_wz_introduction" placeholder="描述" />
              </el-form-item>
              <el-form-item label="适用地区" prop="province">
                <el-select
                  v-model="form.province"
                  remote
                  filterable
                  placeholder="请选择地区"
                  :remote-method="remoteMethod"
                  :loading="selectload"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in cityList"
                    :key="index"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="文章内容" prop="consult_wz_content" class="consultContent">
<!--                <Richtext-->
<!--                  v-model="form.consult_wz_content"-->
<!--                  style="height: 350px"-->
<!--                  :editor-content="form.consult_wz_content"-->
<!--                  :editor-ref="editorRef"-->
<!--                />-->
                <Ckeditor v-model="form.consult_wz_content" :content="form.consult_wz_content"  />
              </el-form-item>
            </el-form>
            <div class="demo-drawer__footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </div>
        </el-drawer>
      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
import {
  listArticleAPi,
  creatArticleAPi,
  updateArticleAPi,
  deleteArticleAPi
} from '@/api/admin/sys-consult'
import { getCity } from '@/api/admin/sys-course'
import { getToken } from '@/utils/auth'
import Richtext from '@/components/richtext'
import Ckeditor from '@/components/richText/ckEditor4.vue'
export default {
  name: 'SysArticleManage',
  components: {
    Richtext,
    Ckeditor
  },
  data() {
    return {
      headers: { Authorization: 'Bearer ' + getToken() },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      sysArticleList: [],
      dateRange: [],

      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        consult_wz_title: undefined,
        consult_wz_start: undefined,
        consult_wz_end: undefined,
        wzType: 2
      },
      // 表单参数
      form: {
        wz_top: 2
      },
      editorRef: 'test',
      // 表单校验
      rules: {
        consult_wz_title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        wz_url: [{ required: true, message: '请上传封面图片' }],
        consult_wz_introduction: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
        province: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        consult_wz_content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      },
      cityList: [],
      selectload: false
    }
  },
  created() {
    this.getList()
    getCity().then(res => {
      this.cityList = res?.data || []
    })
  },
  methods: {
    /** 查询参数列表 */
    getList() {
      this.loading = true
      listArticleAPi(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.sysArticleList = response.data.list
          this.total = response.data.count
          this.loading = false
        }
      )
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    parentIdFormat(row) {
      return this.selectItemsLabel(this.parentIdOptions, row.parentId)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.form = {
        wz_top: 2
      }
      this.open = true
      this.title = '添加文章'
    },
    /** 排序回调函数 */
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (this.order !== '' && this.order !== prop + 'Order') {
        this.queryParams[this.order] = undefined
      }
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
        this.order = prop + 'Order'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
        this.order = prop + 'Order'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.consult_wz_id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const parmas = { ...row, wz_top: Number(row.wz_top) }
      this.form = parmas
      this.open = true
      this.title = '修改文章'
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.updatedAt) {
            updateArticleAPi({
              consult_wz_title: this.form.consult_wz_title,
              wz_url: this.form.wz_url,
              lbt_name_url: this.form.lbt_skip_url,
              consult_wz_content: this.form.consult_wz_content,
              consult_wz_introduction: this.form.consult_wz_introduction,
              consult_wz_id: this.form.consult_wz_id,
              wz_top: this.form.wz_top.toString(),
              province: this.form.province,
              wz_hot:'1',
              wz_type:'2'
            }).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
            return
          }

          creatArticleAPi({
            ...this.form,
            wz_top: this.form.wz_top.toString(),
            wz_hot: '1',
            wz_type:'2'
          }).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg)
              this.open = false
              this.getList()
            } else {
              this.msgError(response.msg)
            }
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = (row.consult_wz_id && [row.consult_wz_id]) || this.ids

      this.$confirm('是否确认删除该数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return deleteArticleAPi({ ids })
        })
        .then(response => {
          if (response.code === 200) {
            this.msgSuccess(response.msg)
            this.open = false
            this.getList()
          } else {
            this.msgError(response.msg)
          }
        })
        .catch(function() {})
    },
    handleRemove() {
      this.form.wz_url = ''
    },
    uploadSuccess(res, file) {
      this.form = {
        ...this.form,
        wz_url: res.data.full_path
      }
    },
    beforeUpload(file) {
      const isLt05M = file.size / 1024 / 1024 < 0.5
      const isJPG = file.type.indexOf('image/') === -1
      if (isJPG) {
        this.$message.error(
          '文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件'
        )
      }
      if (!isLt05M) {
        this.$message.error('上传头像图片大小不能超过 500k!')
      }
      return !isJPG && isLt05M
    },
    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        getCity({ name: query }).then(res => {
          this.cityList = res?.data || []
          this.selectload = false
        })
      } else {
        this.cityList = []
      }
    }
  }
}
</script>
<style lang="scss">
.consultContent {
  height: 450px;
}
</style>
